//
//  tabbarViewController.m
//  tabbarTest
//
//  Created by Kevin Lee on 13-5-6.
//  Copyright (c) 2013年 Kevin. All rights reserved.
//

#import "TabbarViewController.h"
#import "TabbarView.h"
#import "MessageListViewController.h"
#import "AddressBookViewController.h"
#import "PersonalCenterViewController.h"
#import "AppsViewController.h"
#import <AudioToolbox/AudioToolbox.h>
#import "AFHTTPClient.h"
#import "TouristViewController.h"
#import "HomePageController.h"
#import "ABookViewController.h"
#import "PersonalCenterView.h"
#import "MessageSessionDao.h"
#import "QRcodeViewController.h"
#import "ContactDao.h"

#define SELECTED_VIEW_CONTROLLER_TAG 98456345
#define BACKVIEWHEIGHT 200

#define LOGINOUT_DIALG_TAG  19890
#define LOGINOUT_CHECIN_ERR  19819

@interface TabbarViewController (){
    
    NSDate *lastMesageCome;
    NSInteger lastIndex;
}
@property(nonatomic,retain) HomePageController *home;
@property(nonatomic,retain) MessageListViewController *first;
@property(nonatomic,retain) ABookViewController *second;
@property(nonatomic,retain) AppsViewController *third;
@property(nonatomic,retain) PersonalCenterView *forth;

@end

@implementation TabbarViewController

@synthesize drawer;

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.navigationController setNavigationBarHidden:YES];
    
    CGFloat orginHeight = self.view.frame.size.height- TABBARHEIGHT;

    _tabbar = [[TabbarView alloc]initWithFrame:CGRectMake(0,  orginHeight, SCREEN_WIDTH, TABBARHEIGHT)];
    _tabbar.delegate = self;
    _tabbar.tabbar.tabBarDelegate = self;
    [self.view addSubview:_tabbar];
    
    _arrayViewcontrollers = [self getViewcontrollers];
    lastIndex = -1;
    
    //默认显示首页，特殊情况跳转到我的主页
    [_tabbar setCurrentTab:0];
    
    /*if ([_tarbarType isEqualToString:@""]) {
        [_tabbar setCurrentTab:0];
    }
    else
        [_tabbar setCurrentTab:4];
    */

    //获取未读取的消息条数
    int nNumbers = [MessageSessionDao queryMsgCountNoread];
    [_tabbar SetMessageNumber:[NSString stringWithFormat:@"%d",nNumbers] indextar:1];
    
    NSLog(@"-------MAIN ----");
    
    if (kAppDelegate.mqttState !=MQTT_CONNECTTED) {
        NSLog(@"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
        [DE reload];
    }
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    if (kAppDelegate.needRefrsh) {
        [_first refreshTableView];
        [_home LoadApps];
        
        [_second refreshTableView];
        [_third dealPublicAttentionNotifier:nil];
        [_forth refreshTableView];
        //更新下消息数字
        int nNumbers = [MessageSessionDao queryMsgCountNoread];
        [_tabbar SetMessageNumber:[NSString stringWithFormat:@"%d",nNumbers] indextar:1];
        
        kAppDelegate.needRefrsh = NO;
        
    }
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mainrecvMessage:) name:DE.msgBroadcastName object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contactMessage:) name:CONTACT_CHANGE_BROADCAST object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(oterInfoCome:) name:OTHER_CHANGE_BROADCAST object:nil];
        
         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(PublicAttentionNotifier:) name:PUBLIC_ATTENTION_BROADCAST object:nil];
        
        //MESSAGE_DELETE_BROADCAST
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(PublicAttentionNotifier:) name:MESSAGE_DELETE_BROADCAST object:nil];
        
    }
    return self;
}

//20150815(更新消息数字)
- (void)PublicAttentionNotifier:(NSNotification *)notification{
    //更新下消息数字
    int nNumbers = [MessageSessionDao queryMsgCountNoread];
    [_tabbar SetMessageNumber:[NSString stringWithFormat:@"%d",nNumbers] indextar:1];
}

- (void)contactMessage:(NSNotification *)notification{
    
    AddressBookLeftViewController * add = (AddressBookLeftViewController*)kAppDelegate.iCSDrawerController.leftViewController;
    [add refrshOrgData];
    //[_second reloadContactWhenChanger];
    
    [_first refreshTableView];
}

-(void)oterInfoCome:(NSNotification *)notification{
    
    NSDictionary* msg = [notification object];
    if (msg && [@"1" isEqualToString:[msg objectForKey:@"code"]]) {
        
        UIAlertView *aler =[[UIAlertView alloc] initWithTitle:@"提示" message:[msg objectForKey:@"desc"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        aler.tag = LOGINOUT_CHECIN_ERR;
        [aler show];
        return;
    }
    
}

- (void)mainrecvMessage:(NSNotification *)notification{
    
    //设置-声音和震动
    NSDictionary* msg = [notification object];
    NSLog(@"----DE send---recvMessage-----%@",msg);
    BOOL bStartSound = YES;
    //自己发送的不提醒
    if (![DE.userId isEqualToString:[msg objectForKey:@"senderId"]]) {
        //群消息如果做了群免打扰设置，则不震动也没声音
        if([[msg objectForKey:@"messageType"] isEqualToString:@"p2g"])
        {
            //查找本群组的属性
            NSString  *contactid = [[msg objectForKey:@"sessionId"] stringByReplacingOccurrencesOfString:@"p2g_" withString:@""];
            Contact *contact = [ContactDao getContactById:contactid];
            if ([contact.mIS_ACTIVATED isEqualToString:@"0"]) {
                bStartSound = FALSE;
            }
        }
        
        if (bStartSound) {
            if(!lastMesageCome){
                [self soundAndShake];
            }else{
                NSDate *curDate = [NSDate date];
                NSTimeInterval secondsBetweenDates= [curDate timeIntervalSinceDate:lastMesageCome];
                //距离上一次超过3秒才继续响
                if (secondsBetweenDates>=3.0f) {
                    [self soundAndShake];
                }
            }
        }
        
    }
    if ([@"login_out" isEqualToString:[msg objectForKey:@"sessionId"]] ||[@"login_destory" isEqualToString:[msg objectForKey:@"sessionId"]])
    {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        [DE unload];
        DE.userId=@"";
        DE.userPassword=@"";
        kAppDelegate.mqttState = MQTT_NO_CONNECT;
        [DE setGlobalVar:LOGIN_USER_ID value:@""];
        [DE setGlobalVar:LOGIN_USER_PASSWORD value:@""];
        
        UIAlertView *aler =[[UIAlertView alloc] initWithTitle:@"提示" message:@"您的账号在其他地方登录，您已经被强制注销！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        aler.tag = LOGINOUT_DIALG_TAG;
        [aler show];
        
    }else{
        [_first refreshTableView];
    }
 
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (alertView.tag ==LOGINOUT_DIALG_TAG && buttonIndex==0) {
        TouristViewController *info = [[TouristViewController alloc] init];
        [kAppDelegate.iCSDrawerController.navigationController setViewControllers:@[info] animated:YES];
    }
    else  if (alertView.tag ==LOGINOUT_CHECIN_ERR && buttonIndex==0) {
        TouristViewController *info = [[TouristViewController alloc] init];
        [kAppDelegate.iCSDrawerController.navigationController setViewControllers:@[info] animated:YES];

    }
    
}

- (void)soundAndShake{
    lastMesageCome = [NSDate date];

    BOOL blSoundOFF = [@"OFF" isEqualToString:[DE getGlobalVar:ISSOUND]];
    BOOL blShakeOFF = [@"OFF" isEqualToString:[DE getGlobalVar:ISVIBRATE]];
    
     NSLog(@"提交时11111震动提醒：%@",[DE getGlobalVar:ISVIBRATE]);
    
    if (blSoundOFF==NO ) {
         AudioServicesPlaySystemSound(1007);//声音
        //shengin
    }
    if (blShakeOFF==NO ) {
        NSLog(@"1111111111111");
        AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
       
    }

}

-(void) viewDidUnload{
    
    [super viewDidUnload];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

-(NSArray *)getViewcontrollers
{
    NSArray* tabBarItems = nil;
    _home   =  [[HomePageController alloc]init];
    _first  =  [[MessageListViewController alloc]init];
    _second = [[ABookViewController alloc]init];
    //_second.isCreatGroup = NO;
    _third  = [[AppsViewController alloc]init];
    _forth  = [[PersonalCenterView alloc]init];
    
    tabBarItems = [NSArray arrayWithObjects:
                   /*[NSDictionary dictionaryWithObjectsAndKeys:@"homeTabbar1", @"image",@"tabicon_home", @"homeTabbar2", _home, @"viewController", nil]*/
                   [NSDictionary dictionaryWithObjectsAndKeys:@"homeTabbar1", @"image",@"homeTabbar2", @"image_locked", _home, @"viewController", nil],
                   [NSDictionary dictionaryWithObjectsAndKeys:@"messageTabBar1", @"image",@"messageTabBar2", @"image_locked", _first, @"viewController", nil],
                   [NSDictionary dictionaryWithObjectsAndKeys:@"addressTabBar1", @"image",@"addressTabBar2", @"image_locked", _second, @"viewController", nil],
                    [NSDictionary dictionaryWithObjectsAndKeys:@"publicTabBar1", @"image",@"publicTabBar2", @"image_locked", _third, @"viewController", nil],
                   [NSDictionary dictionaryWithObjectsAndKeys:@"personalTarBar1", @"image",@"personalTarBar2", @"image_locked", _forth, @"viewController", nil],nil];
    return tabBarItems;
    
}


//SYTab bar delegate
- (void)tabBar:(SYTabBar *)tabBar didSelectItem:(SYTabBarItem *)item
{
    if (tabBar.tag == MAINTABBAR)
    {
        [self touchBtnAtIndex:item.tag];
    }
}

-(void)touchBtnAtIndex:(NSInteger)index
{
    //通讯录页面有一个左边侧滑页面，需要开启，其他页面关闭侧滑页面
    //这里用的数字编码标示是通讯录页面，需要调整
    //kAppDelegate.iCSDrawerController.canDrawerMove =(index==2);
    //if (index!=2) {
    //    [kAppDelegate.iCSDrawerController open];
    //}
    //如果点击的页面没有变化，不进行处理
    if (lastIndex ==index) {
        return;
    }
    lastIndex =index;
    UIView* currentView = [self.view viewWithTag:SELECTED_VIEW_CONTROLLER_TAG];
    [currentView removeFromSuperview];
    NSDictionary* data = [_arrayViewcontrollers objectAtIndex:index];
    
    UIViewController *viewController = data[@"viewController"];
    viewController.view.tag = SELECTED_VIEW_CONTROLLER_TAG;
    viewController.view.frame = CGRectMake(0,0,SCREEN_WIDTH, SCREEN_HEIGHT);
    [self.view insertSubview:viewController.view belowSubview:_tabbar];
    kAppDelegate.needRefrsh = YES;
}

@end
